package com.demo.spark.rdd;

import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.api.java.function.FlatMapFunction;

import java.util.Arrays;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

public class RddMapPartition {
    public static void main(String[] args) {


        SparkConf config = new SparkConf();
        config.setAppName("rdd map partition");
        config.setMaster("local");

        JavaSparkContext javaSparkContext = new JavaSparkContext(config);
        javaSparkContext.setLogLevel("error");

        List<Integer> data = Arrays.asList(1, 2, 4, 3, 5, 6);
        //RDD有两个分区

        JavaRDD<Integer> javaRDD = javaSparkContext.parallelize(data,2);
        //计算每个分区的合计
        JavaRDD<Integer> mapPartitionsRDD = javaRDD.mapPartitions(new FlatMapFunction<Iterator<Integer>, Integer>() {
            @Override
            public Iterator<Integer> call(Iterator<Integer> integerIterator) throws Exception {
                int isum = 0;
                while(integerIterator.hasNext())
                    isum += integerIterator.next();
                LinkedList<Integer> linkedList = new LinkedList<Integer>();
                linkedList.add(isum);
                linkedList.add(10);
                return linkedList.iterator();
            }
        });

        System.out.println("mapPartitionsRDD~~~~~~~~~~~~~~~~~~~~~~" + mapPartitionsRDD.collect());
    }
}
